package com.sxf.djiuav;

import dji.sdk.keyvalue.key.CameraKey;
import dji.sdk.keyvalue.key.KeyTools;
import dji.sdk.keyvalue.value.camera.CameraMode;
import dji.sdk.keyvalue.value.camera.CameraSDCardState;
import dji.sdk.keyvalue.value.camera.CameraStorageInfos;
import dji.sdk.keyvalue.value.camera.CameraStorageLocation;
import dji.sdk.keyvalue.value.camera.SDCardLoadState;
import dji.sdk.keyvalue.value.common.CameraLensType;
import dji.sdk.keyvalue.value.common.ComponentIndexType;
import dji.sdk.keyvalue.value.common.EmptyMsg;
import dji.v5.common.callback.CommonCallbacks;
import dji.v5.common.error.IDJIError;
import dji.v5.manager.KeyManager;
import dji.v5.utils.common.LogUtils;
import java.util.List;

public class RecordVideo {
    private static final String TAG = "RecordVideo";
    // 定义最小所需空间常量（单位：字节）
    private static final long MIN_REQUIRED_SPACE = 500 * 1024 * 1024; // 500MB
    private DJIApplication app = null;
    private ComponentIndexType cameraIndex = ComponentIndexType.LEFT_OR_MAIN;
    private CameraLensType cameraLensType = CameraLensType.CAMERA_LENS_DEFAULT;

    // 监听器引用，用于移除监听
    private CommonCallbacks.KeyListener<Boolean> recordingStateListener;
    private CommonCallbacks.KeyListener<Integer> recordingTimeListener;

    public RecordVideo(DJIApplication app) {
        this.app = app;
    }

    public RecordVideo(DJIApplication app, ComponentIndexType cameraIndex) {
        this.app = app;
        this.cameraIndex = cameraIndex;
    }

    // 启动录像的函数
    public void startRecording() {
        app.addLog("开始启动录像功能...");
        try {
            // 检查相机模式是否为VIDEO_NORMAL
            checkCameraMode(new CommonCallbacks.CompletionCallback() {
                @Override
                public void onSuccess(){
                    // 检查存储状态
                    checkStorageStatus(new CommonCallbacks.CompletionCallbackWithParam<Boolean>() {
                        @Override
                        public void onSuccess(Boolean hasEnoughSpace) {
                            if (!hasEnoughSpace) {
                                app.addLog("存储空间不足，无法开始录制");
                                return;
                            }

                            // 执行开始录像动作
                            performStartRecord();
                        }

                        @Override
                        public void onFailure(IDJIError error) {
                            app.addLog("检查存储状态失败: " + error.description());
                        }
                    });
                }
                @Override
                public void onFailure(IDJIError error) {
                    app.addLog("设置相机模式失败: " + error.description());
                }
            });
        } catch (Exception e) {
            app.addLog("启动录像功能异常: " + e.getMessage());
            LogUtils.e(TAG, "启动录像功能异常: " + e.getMessage());
        }
    }

    // 停止录像
    public void stopRecording() {
        KeyManager.getInstance().performAction(
                KeyTools.createCameraKey(CameraKey.KeyStopRecord, cameraIndex, cameraLensType),
                new CommonCallbacks.CompletionCallbackWithParam<EmptyMsg>() {
                    @Override
                    public void onSuccess(EmptyMsg result) {
                        removeRecordingListeners();
                        app.addLog("停止录制视频成功");
                    }

                    @Override
                    public void onFailure(IDJIError error) {
                        app.addLog("停止录制视频失败: " + error.description());
                    }
                }
        );
    }

    // 检查并设置相机模式为VIDEO_NORMAL
    private void checkCameraMode(CommonCallbacks.CompletionCallback callback) {
        // 获取当前相机模式
        KeyManager.getInstance().getValue(
                KeyTools.createCameraKey(CameraKey.KeyCameraMode, cameraIndex, cameraLensType),
                new CommonCallbacks.CompletionCallbackWithParam<CameraMode>() {
                    @Override
                    public void onSuccess(CameraMode currentMode) {
                        if (currentMode == CameraMode.VIDEO_NORMAL) {
                            // 已经是视频模式，直接回调成功
                            callback.onSuccess();
                        } else {
                            // 需要切换到视频模式
                            KeyManager.getInstance().setValue(
                                    KeyTools.createCameraKey(CameraKey.KeyCameraMode, cameraIndex, cameraLensType),
                                    CameraMode.VIDEO_NORMAL,
                                    callback
                            );
                        }
                    }

                    @Override
                    public void onFailure(IDJIError error) {
                        callback.onFailure(error);
                    }
                }
        );
    }

    // 检查存储状态
    private void checkStorageStatus(CommonCallbacks.CompletionCallbackWithParam<Boolean> callback) {
        // 获取存储信息
        KeyManager.getInstance().getValue(
                KeyTools.createCameraKey(CameraKey.KeyCameraStorageInfos, cameraIndex, cameraLensType),
                new CommonCallbacks.CompletionCallbackWithParam<CameraStorageInfos>() {
                    @Override
                    public void onSuccess(CameraStorageInfos storageInfos) {
                        if (storageInfos == null) {
                            callback.onSuccess(false);
                            return;
                        }

                        // 获取当前存储位置
                        CameraStorageLocation currentLocation = storageInfos.getCurrentStorageType();

                        // 查找当前存储位置的信息
                        List<dji.sdk.keyvalue.value.camera.CameraStorageInfo> storageList =
                                storageInfos.getCameraStorageInfoList();

                        if (storageList == null || storageList.isEmpty()) {
                            callback.onSuccess(false);
                            return;
                        }

                        for (dji.sdk.keyvalue.value.camera.CameraStorageInfo info : storageList) {
                            if (info.getStorageType() == currentLocation) {
                                // 检查存储状态和可用空间
                                boolean isReady = checkStorageReady(info);
                                callback.onSuccess(isReady);
                                return;
                            }
                        }

                        callback.onSuccess(false);
                    }

                    @Override
                    public void onFailure(IDJIError error) {
                        callback.onFailure(error);
                    }
                }
        );
    }

    // 检查存储是否就绪
    private boolean checkStorageReady(dji.sdk.keyvalue.value.camera.CameraStorageInfo storageInfo) {
        // 获取存储状态
        SDCardLoadState state = storageInfo.getStorageState();
        long availableSpace = storageInfo.getStorageLeftCapacity();

        // 检查存储状态和可用空间
        boolean isReady = (state == SDCardLoadState.INSERTED) &&
                availableSpace > MIN_REQUIRED_SPACE;

        return isReady;
    }

    // 执行开始录像动作
    private void performStartRecord() {
        KeyManager.getInstance().performAction(
                KeyTools.createCameraKey(CameraKey.KeyStartRecord, cameraIndex, cameraLensType),
                new CommonCallbacks.CompletionCallbackWithParam<EmptyMsg>() {
                    @Override
                    public void onSuccess(EmptyMsg result) {
                        app.addLog("开始录制视频成功");
                        // 设置录制状态监听
                        setupRecordingStatusListener();
                    }

                    @Override
                    public void onFailure(IDJIError error) {
                        app.addLog("开始录制视频失败: " + error.description());
                    }
                }
        );
    }

    // 设置录制状态监听
    private void setupRecordingStatusListener() {
        try {
            // 监听录制状态
            recordingStateListener = new CommonCallbacks.KeyListener<Boolean>() {
                @Override
                public void onValueChange(Boolean oldValue, Boolean newValue) {
                    if (newValue != null) {
                        String status = newValue ? "正在录制" : "未在录制";
                        String msg = "录像状态: " + status;
                        LogUtils.d(TAG, msg);
                        app.addLog(msg);
                    }
                }
            };

            KeyManager.getInstance().listen(
                    KeyTools.createCameraKey(CameraKey.KeyIsRecording, cameraIndex, cameraLensType),
                    this,
                    recordingStateListener
            );

            // 监听录制时间
            recordingTimeListener = new CommonCallbacks.KeyListener<Integer>() {
                @Override
                public void onValueChange(Integer oldValue, Integer newValue) {
                    if (newValue != null) {
                        String msg = "已录制时间: " + newValue + "秒";
                        LogUtils.d(TAG, msg);
                        app.addLog(msg);
                    }
                }
            };

            KeyManager.getInstance().listen(
                    KeyTools.createCameraKey(CameraKey.KeyRecordingTime, cameraIndex, cameraLensType),
                    this,
                    recordingTimeListener
            );
        } catch (Exception e) {
            app.addLog("设置录像状态监听错误: " + e.getMessage());
            LogUtils.e(TAG, "设置录像状态监听错误: " + e.getMessage());
        }
    }

    // 移除监听器
    private void removeRecordingListeners() {
        try {
            if (recordingStateListener != null) {
                KeyManager.getInstance().cancelListen(
                        KeyTools.createCameraKey(CameraKey.KeyIsRecording, cameraIndex, cameraLensType),
                        recordingStateListener
                );
            }

            if (recordingTimeListener != null) {
                KeyManager.getInstance().cancelListen(
                        KeyTools.createCameraKey(CameraKey.KeyRecordingTime, cameraIndex, cameraLensType),
                        recordingTimeListener
                );
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "移除监听器错误: " + e.getMessage());
        }
    }

    // 获取当前录制时间
    public void getRecordingTime(CommonCallbacks.CompletionCallbackWithParam<Integer> callback) {
        KeyManager.getInstance().getValue(
                KeyTools.createCameraKey(CameraKey.KeyRecordingTime, cameraIndex, cameraLensType),
                callback
        );
    }

    // 检查是否正在录制
    public void isRecording(CommonCallbacks.CompletionCallbackWithParam<Boolean> callback) {
        KeyManager.getInstance().getValue(
                KeyTools.createCameraKey(CameraKey.KeyIsRecording, cameraIndex, cameraLensType),
                callback
        );
    }

    // 清理资源
    public void cleanup() {
        removeRecordingListeners();
    }
}
